package com.erp.produce.service.impl;

import com.erp.common.util.ServiceUtil;
import com.erp.common.util.StringUtil;
import com.erp.common.util.TimeUtil;
import com.erp.produce.dao.OrderDao;
import com.erp.produce.entity.Order;
import com.erp.stock.dao.FinishedGoodsInventoryDao;
import com.erp.produce.service.FinishedGoodsInventoryService;
import com.erp.produce.service.OrderService;
import com.erp.stock.entity.FinishedGoodsInventory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class FinishedGoodsInventoryServiceImpl implements FinishedGoodsInventoryService {
    @Autowired
    FinishedGoodsInventoryDao dao;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderDao orderDao;

    @Override
    public Boolean saveList(List<FinishedGoodsInventory> list) {
        return dao.saveAll(list) != null;
    }

    @Override
    @Transactional
    public Boolean finishedGoodsOutOfStock(Long orderId) {
        List<FinishedGoodsInventory> list = dao.findAllByOrderId(orderId);
        list.forEach(entity->{
            entity.setOutOfStockTime(TimeUtil.now());
            System.out.println(entity);
        });
        dao.saveAll(list);
        Boolean success = orderService.changeStatus(8, orderId);
        return  success;
    }


    @Override
    public Boolean update(FinishedGoodsInventory finishedGoodsInventory) {
        return dao.saveAndFlush(finishedGoodsInventory) != null;
    }

    @Override
    public Boolean add(FinishedGoodsInventory finishedGoodsInventory) {
        return dao.save(finishedGoodsInventory) != null;
    }

    @Override
    public Boolean deleteIds(Long[] ids) {
        return ServiceUtil.deleteIds(ids,dao);
    }

    @Override
    public List<FinishedGoodsInventory> listPage(int page, int size) {
        return dao.findAll(PageRequest.of(page, size,new Sort(Sort.Direction.ASC,"id"))).getContent();
    }

    @Override
    public List<FinishedGoodsInventory> listPageLike(int page, int size, String column) {
        List<FinishedGoodsInventory> list = new ArrayList<>();
        List<Order> orders = orderDao.findAllByCustomerNameLike(StringUtil.addLike(column));
        for (Order order : orders) {
            List<FinishedGoodsInventory> subList = dao.findAllByOrderId(order.getId());
            list.addAll(subList);
        }
        return list;
    }
}
